Visualized as as three rows and four columns:
But the physical memory is linear, and we assume the integer takes 2 bytes.
A[0] = 200 to 201
A[1] = 202 to 203
A[2] = 204 to 205
A[3] = 204 to 205
.................
.................
A[22] = 220 to 221
A[23] = 222 to 223
So,
int A[3][4] = 12 bytes
12 x 2 bytes per integer = 24 bytes
Memory is allocated as a single dimensional array, but the compiler allows us to acces it as a two dimensional array, with row and column number, with TWO INDEXES
#include <iostream>
#include <climits>
#include <math.h>
using namespace std;
//Must declare and initialize at same time, if you want to use the shortened form
//int A[3][4];
int A[3][4]={
1,2,3,4,
4,5,3,5,
7,4,5,6
};
for (int i = 0; i < 3; i++){
for (int j = 0; j < 4; j++){
cout<<A[i][j]<<" ";
}
cout<<endl;
}
Remember: We want two rows and three columns
int *A[3]
But what does this mean? This is not an array of integers, its an array of integer pointers
This is an array of three pointers.
But keeping to what we need: Three 3 rows and 4 columns
Picture*
This will be our rows
int *A1[3];
These will be our columns
A1[0] = new int[4];
A1[1] = new int[4];
A1[2] = new int[4];
A1[0][0]=5;A1[0][1]=5;A1[0][2]=5;A1[0][3]=5;
A1[1][0]=6;A1[1][1]=6;A1[1][2]=6;A1[1][3]=6;
A1[2][0]=7;A1[2][1]=7;A1[2][2]=7;A1[2][3]=7;
Normally, we have a pointer in the STACK, to create (point to) an array in HEAP of certain size. Now we have an array of pointers in stack, so make up our rows. And for each row, eg. A[0] we create a new four dimensional array in heap, to present the columns.
for (int i = 0; i < 3; i++){
for (int j = 0; j < 4; j++){
cout<<A1[i][j]<<" ";
}
cout<<endl;
}
Remember: We want two rows and three columns
Previously the row int array pointers were in the STACK, pointing to the column pointers in the HEAP.
Now both row and column will be in the HEAP.
Through the use of double pointers. Lets explore.
int **A
We use two ** (asterisks)...to signify this A will be and array in HEAP
And A is now treated as variable, still in STACK, but will now point to rows and columns in the HEAP.
For the rows:
A=new int *[3];
For the columns:
A[0]=new int[4];
A[1]=new int[4];
A[3]=new int[4];
Setup the double pointer, to signify that A will be an array in HEAP. That is it will be redefined later on.
int **A2;
Create new array pointer in heap of size 3, redefining A
A2=new int *[3];
Create the column arrays as we did with method 2
A2[0]=new int[4];
A2[1]=new int[4];
A2[2]=new int[4];
A2[0][0]=4;A2[0][1]=4;A2[0][2]=4;A2[0][3]=4;
A2[1][0]=9;A2[1][1]=9;A2[1][2]=9;A2[1][3]=9;
A2[2][0]=3;A2[2][1]=3;A2[2][2]=3;A2[2][3]=3;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 4; j++){
cout<<A2[i][j]<<" ";
}
cout<<endl;
}
delete []A2;
A2=nullptr;